package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.pojo.Employee;
import com.itheima.pojo.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    //匹配通配符 : /**
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取访问路径
        String url = req.getRequestURI();
        // System.out.println("url:"+url);
        //可以放行的静态资源
        String[] urls = {"/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};
        boolean check = check(urls, url);
        if (check) {
            //允许放行
            filterChain.doFilter(req, resp);
            return;
        }
        //判断用户是否登录,登录放行
        HttpSession session = req.getSession();
        //Employee one = (Employee) session.getAttribute("one");
        //if (one!=null){
        //    filterChain.doFilter(req,resp);
        //    return;
        //}

        if (session.getAttribute("one") != null) {
            long id = (long) session.getAttribute("one");
            BaseContext.setCurrentId(id);
            filterChain.doFilter(req, resp);
            return;
        }

        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    //判断访问路径是否可以放行
    //访问路径与可以被放行路径比较
    public boolean check(String[] urls, String url) {
        for (String ur : urls) {
            boolean match = PATH_MATCHER.match(ur, url);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
